package com.ruoyi.system.outto.goods.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.gameAttr.service.IGameAttributeService;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.V2.inter.mapper.SelectPushMapper;
import com.ruoyi.system.V2.inter.mapper.SalePartnerMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.goods.MONIMIMAAPI;
import com.ruoyi.system.sms.service.ISendSms;
import com.ruoyi.system.utils.MiMaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MONIMIMAApiImpl implements MONIMIMAAPI {

    @Resource
    private IGameAttributeService gameAttributeService;
    @Resource
    InterAttrMapper interAttrMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;
    @Resource
    private SalePartnerMapper salePartnerMapper;

    @Autowired
    private ISendSms sendSms;
    @Autowired
    private SelectPushMapper selectPushMapper;

    public static void main(String[] args) {
        String body = HttpRequest.get("https://mh.poxiaowy.com/generator/chuanyue/chuanyueApiController.php?pg=qqLogin").execute().body();
        System.out.println(body);
    }

    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String server) {

        JSONObject serjsonObject = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = serjsonObject.getString("interServeReqs");
        String qufuid = "";
        List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
        if (Objects.equals(goodsInfoAndAttrValueDto.getGameType(), "0")) {
            qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId() + "";
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (qufuid.contains(ydServeId)) {
                        params.put("partition_id", object.getString("id"));
                        break;
                    }
                }
            }
        } else {
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (ydServeId.contains(goodsInfoAndAttrValueDto.getGroupId().toString())) {
                        String interServerRes = object.getString("interServerRes");
                        List<JSONObject> twoServer = JSONObject.parseArray(interServerRes, JSONObject.class);
                        for (JSONObject object2 : twoServer) {
                            ydServeId = object2.getString("YdServeId");
                            if(StringUtils.isNotEmpty(ydServeId)) {
                                ydServeId = ydServeId.replace(",", "").replace(" ", "");
                                if (StringUtils.equals(ydServeId, goodsInfoAndAttrValueDto.getServerId() + "")) {
                                    params.put("partition_id", object2.getString("id"));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String radioAttr) {

        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (!CollectionUtils.isEmpty(jsonObjects)) {
            /**
             * 1、先查询自定义中所有单选的字段
             * 2、再查该账号单选字段中的选项
             * 3、再去接口属性匹配表过滤
             */
            GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
            gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
            gameAttrTemplate.setIsEnable("0");
            gameAttrTemplate.setFieldType("radio");
            List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
            Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();


            List<JSONObject> defObjects = new ArrayList<>();
            defObjects.addAll(jsonObjects);
            for (JSONObject object : jsonObjects) {
                for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                    String aavName = attrTemplate.getAavName();
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (aavName.equals(name)) {
                            //一级属性
                            //注意 YdConfigId 对应的是 f字段对应的 id
                            if (StringUtils.isNotEmpty(object.getString("YdConfigId"))) {
                                if (object.getString("YdConfigId").contains(attrTemplate.getId() + "")) {
                                    String InterConfigId = object.getString("InterConfigId");
                                    defObjects.remove(object);//如果匹配上，则去掉
                                    String interRadioReqs1 = object.getString("interRadioReqs");
                                    List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                                    declaredField.setAccessible(true);
                                    try {
                                        //获取选择的值 例如  实名中的可二次
                                        Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                        String oneValue = String.valueOf(o);
                                        List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> StringUtils.isNotEmpty(j.getString("YdConfigId")) ? j.getString("YdConfigId").contains(oneValue) : "1".contains(oneValue)).collect(Collectors.toList());
                                        String interConfigName = object.getString("InterConfigName");
                                        String defaultValue = object.getString("defaultValue");
                                        if (CollectionUtils.isEmpty(twoAttr)) {
                                            if (StringUtils.isNotEmpty(defaultValue)) {
                                                params.put(InterConfigId, defaultValue);
                                            }
                                        }
                                        if (!CollectionUtils.isEmpty(twoAttr)) {
                                            JSONObject jsonObject2 = twoAttr.get(0);
                                            String interConfigId2 = jsonObject2.getString("InterConfigId");
                                            params.put(InterConfigId, interConfigId2);
                                        }else if(StringUtils.isEmpty(object.getString("defaultValue"))){
                                            String interServerRes = object.getString("interServerRes");
                                            Object o1 = JSONArray.parseArray(interServerRes).get(0);
                                            String interConfigId2 = JSONObject.parseObject(o1.toString()).getString("InterConfigId");
                                            params.put(InterConfigId, interConfigId2);
                                        }
                                    } catch (Exception e) {
                                        throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //开始匹配默认值
            for (JSONObject object : defObjects) {
                HashMap<String, Object> mateMap = new HashMap<>();
                String id = object.getString("id");
                String interRadioReqss = object.getString("interRadioReqs");
                List<JSONObject> jsonObjectss = JSONObject.parseArray(interRadioReqss, JSONObject.class);
                for (JSONObject jsonObject1 : jsonObjectss) {
                    if (StringUtils.isNotEmpty(jsonObject1.getString("defaultValue"))) {
                        params.put(id, jsonObject1.getString("defaultValue"));
                        break;
                    }
                }
            }
            //========================单选属性匹配结束=====================//
        }
    }

    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String checkAttr) {
        //========================开始匹配多选属性=====================//
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);

        for (JSONObject object : checkJsonList) {
            String InterConfigId = object.getString("InterConfigId");
            List<String> list = new ArrayList<>();
            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        declaredField.setAccessible(true);

                        String ydConfigIdLeveOne = object.getString("YdConfigId");
                        if (StringUtils.isNotEmpty(ydConfigIdLeveOne)) {

                            String[] split2 = ydConfigIdLeveOne.split(",");
                            List<String> list2 = new ArrayList<>();
                            for (String s : split2) {
                                s = s.replace(" ", "");
                                list2.add(s);
                            }
                            if (list2.contains(attrTemplate.getId() + "")) {
                                Object o = null;
                                try {
                                    o = declaredField.get(goodsInfoAndAttrValueDto);
                                } catch (IllegalAccessException e) {
                                    throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                                String oneValue = String.valueOf(o);
                                //一级属性
                                String ydConfigId = object.getString("YdConfigId");
                                String InterConfigName = object.getString("InterConfigName");
                                if (StringUtils.isNotEmpty(ydConfigId)) {
                                    ydConfigId = ydConfigId.replace(" ","");
                                    String[] split = ydConfigId.split(",");
                                    //一级属性已经匹配，开始匹配二级属性
                                    if (Arrays.asList(split).contains(attrTemplate.getId() + "")) {
                                        String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
//                                        String interCheckBoxReqsStr = object.getString("interServerRes");
                                        //开始匹配二级属性
                                        List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                                        /**
                                         * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                                         */
                                        for (JSONObject jsonObject1 : jsonObjects2) {
                                            if (StringUtils.isNotEmpty(oneValue)) {
                                                String[] split1 = oneValue.split(",");
                                                String ydConfigId1 = jsonObject1.getString("YdConfigId");
                                                if (StringUtils.isNotEmpty(ydConfigId1)) {
                                                    ydConfigId1 = ydConfigId1.replace(" ", "");
                                                    for (String s : split1) {
                                                        if (goodsInfoAndAttrValueDto.getGameName().equals("原神")) {
                                                            GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(s));
                                                            GameAttribute gameAttribute2 = gameAttributeMapper.selectGameAttributeById(gameAttribute1.getParentId());
                                                            s = gameAttribute2.getId().toString();
                                                        }
                                                        if (goodsInfoAndAttrValueDto.getGameName().equals("崩坏星穹铁道")) {
                                                            GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(s));
                                                            GameAttribute gameAttribute2 = gameAttributeMapper.selectGameAttributeById(gameAttribute1.getParentId());
                                                            s = gameAttribute2.getId().toString();
                                                        }
                                                        if (Objects.equals(s, ydConfigId1)) {
                                                            String InterConfigId2 = jsonObject1.getString("InterConfigId");
                                                            list.add(InterConfigId2);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    throw new GlobalException("属性参数错误，请匹配后重新配置");
                                }
                            }
                        }
                    }
                }
            }
            if (!CollectionUtils.isEmpty(list)) {
                params.put(InterConfigId, list.stream().collect(Collectors.joining(",")));
            }
        }
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(checkJsonList);
        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            String id = object.getString("id");
            String defaultValue = object.getString("defaultValue");
            if(StringUtils.isNotEmpty(defaultValue)) {
                String interRadioReqss = object.getString("interCheckBoxReqs");
                List<JSONObject> jsonObjectss = JSONObject.parseArray(interRadioReqss, JSONObject.class);
                for (JSONObject jsonObject1 : jsonObjectss) {
                    if (StringUtils.isNotEmpty(jsonObject1.getString("defaultValue"))) {
                        params.put(id, jsonObject1.getString("defaultValue"));
                        break;
                    }
                }
            }
        }
        //========================多选属性匹配完成=====================//
    }

    private void builderInputAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String inputAttr) {
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

        //========================开始匹配输入框=====================//
        JSONObject jsonObject1 = JSONObject.parseObject(inputAttr);
        String inputJson = jsonObject1.getString("inputJson");
        List<JSONObject> jsonObjects1 = JSONObject.parseArray(inputJson, JSONObject.class);
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        ArrayList types = new ArrayList<>();
        types.add("number");
        types.add("input");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> inputTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(jsonObjects1);
        for (JSONObject object : jsonObjects1) {
            for (GameAttrTemplate inputTemplate : inputTemplates) {
                String aavName = inputTemplate.getAavName();
                if (Objects.equals(object.getString("aavName"), inputTemplate.getAavName())) {
                    defInputObjects.remove(object);
                    String aavNameInter = object.getString("interName");
                    String interId = object.getString("interId");
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (Objects.equals(aavName, name)) {
                            declaredField.setAccessible(true);
                            String oneValue = null;
                            try {
                                oneValue = (String) declaredField.get(goodsInfoAndAttrValueDto);
                            } catch (IllegalAccessException e) {
                                throw new GlobalException("3属性参数错误，请匹配后重新配置");
                            }
                            if (StringUtils.isNotEmpty(oneValue)) {
//                                if (oneValue.equals("0")) {
//                                    oneValue = "1";
//                                }
                                params.put(interId, oneValue);
                            }
                        }
                    }
                }

            }
        }
        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            String id = object.getString("id");
            String defaultValue = object.getString("defaultValue");
            if (StringUtils.isNotEmpty(defaultValue)) {
                params.put(id, 1);
            }
            if(object.getString("name").equals("游戏等级")){
                params.put(id, 30);
            }
            if(object.getString("name").equals("角色等级")){
                params.put(id, 30);
            }
        }
    }


    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, InterAttr interAttr, SalePartner salePartner) {
        Map<String, Object> params = new TreeMap<>();

        if (goodsInfoAndAttrValueDto.getGameName().equals("王者荣耀")) {
            params.put("sub_cate_id", 290);
            params.put("trade_relation_id", 1203);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("和平精英")) {
            params.put("sub_cate_id", 291);
            params.put("trade_relation_id", 1237);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟")) {
            params.put("sub_cate_id", 292);
            params.put("trade_relation_id", 1216);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟(手游)")) {
            params.put("sub_cate_id", 781);
            params.put("trade_relation_id", 1715);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("枪战王者")) {
            params.put("sub_cate_id", 293);
            params.put("trade_relation_id", 1232);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("金铲铲之战")) {
            params.put("sub_cate_id", 774);
            params.put("trade_relation_id", 2329);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("永劫无间")) {
            params.put("sub_cate_id", 728);
            params.put("trade_relation_id", 7242);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("永劫无间手游")) {
            params.put("sub_cate_id", 1667);
            params.put("trade_relation_id", 3493);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("原神")) {
            params.put("sub_cate_id", 305);
            params.put("trade_relation_id", 1694);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("崩坏星穹铁道")) {
            params.put("sub_cate_id", 1168);
            params.put("trade_relation_id", 2812);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("火影忍者")) {
            params.put("sub_cate_id", 296);
            params.put("trade_relation_id", 1385);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("暗区突围")) {
            params.put("sub_cate_id", 865);
            params.put("trade_relation_id", 2629);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("穿越火线")) {
            params.put("sub_cate_id", 337);
            params.put("trade_relation_id", 1455);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("三角洲行动")) {
            params.put("sub_cate_id", 1535);
            params.put("trade_relation_id", 3383);
            params.put("partition_id", 333265);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("使命召唤手游")) {
            params.put("sub_cate_id", 569);
            params.put("trade_relation_id", 2162);
        }

        params.put("goods_cate_id", Long.valueOf(interAttr.getInterGameId()));
        params.put("promotion_rate", 0);
        params.put("trade_type_id", 2);


        params.put("price", goodsInfoAndAttrValueDto.getPrice());

        //开始匹配区服属性
        builderServer(goodsInfoAndAttrValueDto, params, interAttr.getServer());

        JSONObject goods_options = new JSONObject();

        //开始匹配单选属性
        builderRadioAttr(goodsInfoAndAttrValueDto, goods_options, interAttr.getRadioAttr());
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto, goods_options, interAttr.getCheckAttr());
        //开始匹配输入框属性
        builderInputAttr(goodsInfoAndAttrValueDto, goods_options, interAttr.getInputAttr());

        if (goodsInfoAndAttrValueDto.getGameName().equals("枪战王者")) {
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF2())) {
                GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF2()));
                goods_options.put("2422", gameAttribute1.getFieldName().replace("V", ""));
            }
        }
        params.put("goods_options", goods_options.toJSONString());

        //图片待处理
        List<String> goods_media = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        String titleImg = goodsInfoAndAttrValueDto.getTitleImg();
        String s = MiMaUtil.uploadImg(titleImg);
        jsonObject.put("media_type", "1");
        jsonObject.put("url", JSONObject.parseObject(s).getString("key"));
        jsonObject.put("ut", String.valueOf(System.currentTimeMillis()));
        jsonObject.put("is_main", 1);
        jsonObject.put("sort", 0);
        goods_media.add(jsonObject.toJSONString());

        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        Collections.shuffle(infoImgs);
        if (infoImgs.size() > 10) {
            infoImgs = infoImgs.subList(0, 9);
        }
        if (infoImgs.size() < 3) {
            String imgUrl = infoImgs.get(0).getImgUrl();
            GoodsInfoImg goodsInfoImgs = new GoodsInfoImg();
            goodsInfoImgs.setImgUrl(imgUrl);
            infoImgs.add(goodsInfoImgs);
            goodsInfoImgs = new GoodsInfoImg();
            goodsInfoImgs.setImgUrl(imgUrl);
            infoImgs.add(goodsInfoImgs);
            goodsInfoImgs = new GoodsInfoImg();
            goodsInfoImgs.setImgUrl(imgUrl);
            infoImgs.add(goodsInfoImgs);
        }
        for (GoodsInfoImg goodsInfoImg1 : infoImgs) {
            jsonObject = new JSONObject();
            String ss = "";
            try {
                ss = MiMaUtil.uploadImg(goodsInfoImg1.getImgUrl());
            }catch (Exception e){

            }
            if(StringUtils.isNotEmpty(ss)) {
                jsonObject.put("media_type", "1");
                jsonObject.put("url", JSONObject.parseObject(ss).getString("key"));
                jsonObject.put("ut", String.valueOf(System.currentTimeMillis()));
                jsonObject.put("is_main", "0");
                jsonObject.put("sort", 0);
                goods_media.add(jsonObject.toJSONString());
            }
        }

        params.put("goods_media", goods_media);

        params.put("goods_desc", goodsInfoAndAttrValueDto.getDes().length() > 2000 ? goodsInfoAndAttrValueDto.getDes().substring(0, 1999) : goodsInfoAndAttrValueDto.getDes());
//        JSONObject form = new JSONObject();
//        form.put("account",goodsInfoAndAttrValueDto.getAccountNumber());
//        form.put("password","123456");
//        params.put("form", form.toJSONString());
        params.put("contact_phone", salePartner.getSaleKey());
        params.put("account", goodsInfoAndAttrValueDto.getAccountNumber());
        params.put("password", String.valueOf(System.currentTimeMillis()));
        params.put("login_type", 0);
        params.put("goods_name", goodsInfoAndAttrValueDto.getDes().length() > 40 ? goodsInfoAndAttrValueDto.getDes().substring(0, 39) : goodsInfoAndAttrValueDto.getDes());
        params.put("open_lose", 0);
        params.put("specs_type", 3);
        params.put("is_normal", 0);
        params.put("seller_guarantee_days", -1);
        params.put("income_type", "");
        return params;
    }


    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        //属性匹配
//        String substring = salePartner.getSaleName().substring(salePartner.getSaleName().indexOf("_")+1);
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(salePartner.getSaleName(), goodsInfoAndAttrValueDto.getGameId());
        if (StringUtils.isEmpty(interAttr.getInterGameId())) {
            throw new GlobalException("该游戏属性暂未匹配!!!" + goodsInfoAndAttrValueDto.getGameName());
        }

        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, interAttr, salePartner);
//        String login = MiMaUtil.login(salePartner.getSaleKey(), salePartner.getOther());
//        String data1 = JSONObject.parseObject(login).getString("data");
//        String authorization = JSONObject.parseObject(data1).getString("authorization");
//        String authorization = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxNzI4MDczLCJuaWNrbmFtZSI6Ilx1NjhhNlx1OThkZVx1NmMzOFx1NGU0NVx1NTMwNVx1OGQ1NFx1NGUxM1x1ODQyNSIsInBob25lIjoiMTM4MzA1ODE0MzciLCJ3eF91bmlvbmlkIjoib05oYVJ4SUs2NjhUNW5oSF9odmNNS1g1U01RVSIsImJ1c2luZXNzX2NvdW50IjoyLCJyZWNvbW1lbmRfbW9kZWwiOiJPcmlnaW4iLCJyZWNvbW1lbmRfbW9kZWxfdGltZSI6MTY5NjQ2OTkwMCwiaWF0IjoxNzMyMzQ1MDY0LCJleHAiOjE3MzIzNDg2NjQsImtleSI6ODk2M30.MjVAELQtmlFjhab2cPSSy9Ts4xmL03Fvz_aZ10YmohU";
//        System.out.println(authorization);
        log.info("密马添加接口请求参数={}", JSONObject.toJSONString(params));
//        String url = "https://api.mimaapp.cn/v4/goods/merchant_release_goods";
        String url = "https://api.mimaapp.cn/v8/goods/release";
        String result = HttpRequest.post(url)
                .header("Authorization", salePartner.getTwoOther())
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json")
                .header("device", "1")
//                .header("Origin","https://h5.mimaapp.cn")
//                .header("Pragma","no-cache")
//                .header("Referer","https://h5.mimaapp.cn/")
//                .header("Sec-Fetch-Dest","empty")
//                .header("Sec-Fetch-Mode","cors")
//                .header("Sec-Fetch-Site","same-site")
//                .header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
//                .header("cs","")
//                .header("et","opnYeMLBhpfAvh/zEbCy/FnIhTrhcpLAKu+I6Mm8jE7zzbd1z1ZR2wMC1lwa42zdcW1mLRaq5NFI5j3nZbkPmg==")
//                .header("fp","AtuAHBmeOp5ABhBQQRaHDgzGG2ye5jLy|v1|ca4ddb39add7cf36fa6edede8db40555")
//                .header("sec-ch-ua","\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"")
//                .header("sec-ch-ua-mobile","?0")
//                .header("sec-ch-ua-platform","\"Windows\"")
                .body(JSONObject.toJSONString(params))
                .execute()
                .body();


        log.info("密马添加接口返回参数={}", result);
        System.out.println(MapUntils.unicodeToString(result));
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"700401".equals(resultJson.getString("code"))) {
            resultMap.put("code", 500);
            if (
                    "50000".equals(resultJson.getString("code")) ||
                    "50109".equals(resultJson.getString("code"))
            ) {
                //重新获取密钥
                try {
                    String login = MiMaUtil.login(salePartner.getSaleKey(), salePartner.getOther());
                    String data1 = JSONObject.parseObject(login).getString("data");
                    String authorization = JSONObject.parseObject(data1).getString("authorization");
                    salePartner.setTwoOther(authorization);
                    salePartnerMapper.updateSalePartner(salePartner);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            resultMap.put("code", 200);
            String data = resultJson.getString("data");
            String page = JSONObject.parseObject(data).getString("page");
            String paramss = JSONObject.parseObject(page).getString("params");
            String goodsId = JSONObject.parseObject(paramss).getString("goodsId");
            resultMap.put("outId", goodsId);
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        //属性匹配
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(salePartner.getSaleName(), goodsInfoAndAttrValueDto.getGameId());
        if (StringUtils.isEmpty(interAttr.getInterGameId())) {
            throw new GlobalException("该游戏属性暂未匹配!!!" + goodsInfoAndAttrValueDto.getGameName());
        }

        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, interAttr, salePartner);
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        if (CollectionUtils.isEmpty(artRecs)) {
            throw new GlobalException("当前商品为上架 不可编辑!");
        }
        params.put("goods_id", artRecs.get(0).getOutid());
        log.info("密马编辑参数={}", JSONObject.toJSONString(params));
//        String url = "https://api.mimaapp.cn/v4/goods/merchant_release_goods";
        String url = "https://api.mimaapp.cn/v8/goods/release";
        String result = HttpRequest.post(url)
                .header("Authorization", salePartner.getTwoOther())
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json;charset=UTF-8")
                .header("device", "1")
                .header("Origin", "https://h5.mimaapp.cn")
                .header("Pragma", "no-cache")
                .header("Referer", "https://h5.mimaapp.cn/")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-site")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
                .header("cs", "")
                .header("et", "opnYeMLBhpfAvh/zEbCy/FnIhTrhcpLAKu+I6Mm8jE7zzbd1z1ZR2wMC1lwa42zdcW1mLRaq5NFI5j3nZbkPmg==")
                .header("fp", "AtuAHBmeOp5ABhBQQRaHDgzGG2ye5jLy|v1|ca4ddb39add7cf36fa6edede8db40555")
                .header("sec-ch-ua", "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .body(JSONObject.toJSONString(params))
                .execute()
                .body();


        log.info("密马编辑接口返回参数={}", result);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"700401".equals(resultJson.getString("code"))) {
            resultMap.put("code", 500);
            if(result.contains("您的登录信息已失效")){
                //重新获取密钥
                try {
                    String login = MiMaUtil.login(salePartner.getSaleKey(), salePartner.getOther());
                    String data1 = JSONObject.parseObject(login).getString("data");
                    String authorization = JSONObject.parseObject(data1).getString("authorization");
                    salePartner.setTwoOther(authorization);
                    salePartnerMapper.updateSalePartner(salePartner);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            resultMap.put("code", 200);
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> params = new TreeMap<>();
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        if (CollectionUtils.isEmpty(artRecs)) {
            throw new GlobalException("当前商品为上架 不可删除!");
        }
        params.put("goods_id", artRecs.get(0).getOutid());
        log.info("密马编辑参数={}", JSONObject.toJSONString(params));
        String url = "https://api.mimaapp.cn/v1/goods/delete";
        String result = HttpRequest.post(url)
                .header("Authorization", salePartner.getTwoOther())
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("content-length", "22")
                .header("Content-Type", "application/json;charset=UTF-8")
                .header("device", "1")
                .header("Origin", "https://h5.mimaapp.cn")
                .header("Pragma", "no-cache")
                .header("Referer", "https://h5.mimaapp.cn/")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-site")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
                .header("cs", "")
                .header("et", "opnYeMLBhpfAvh/zEbCy/FnIhTrhcpLAKu+I6Mm8jE7zzbd1z1ZR2wMC1lwa42zdcW1mLRaq5NFI5j3nZbkPmg==")
                .header("fp", "AtuAHBmeOp5ABhBQQRaHDgzGG2ye5jLy|v1|ca4ddb39add7cf36fa6edede8db40555")
                .header("sec-ch-ua", "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .body(JSONObject.toJSONString(params))
                .execute()
                .body();


        log.info("密马编辑接口返回参数={}", result);
        System.out.println(MapUntils.unicodeToString(result));
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"0".equals(resultJson.getString("code"))) {
            resultMap.put("code", 500);
            if(result.contains("您的登录信息已失效")){
                //重新获取密钥
                try {
                    String login = MiMaUtil.login(salePartner.getSaleKey(), salePartner.getOther());
                    String data1 = JSONObject.parseObject(login).getString("data");
                    String authorization = JSONObject.parseObject(data1).getString("authorization");
                    salePartner.setTwoOther(authorization);
                    salePartnerMapper.updateSalePartner(salePartner);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            resultMap.put("code", 200);
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    private static String r() {
        Random random = new Random();
        int min = 1000000;
        int max = 9999999;

        Integer randomNumber = random.nextInt(max - min + 1) + min;
        System.out.println("随机六位: " + randomNumber);
        return randomNumber.toString();
    }

    //    static String upLoadImg(String img){
//        String url = "https://kejinlianmeng.com/api_v1/system/upload/image";
//        File file = null;
//        try {
//            BufferedImage image = ImageIO.read(new URL(img).openStream());
//            byte[] bytes = ImgUntil.bufferedImageToByteArray(image);
//            file = convert(bytes);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        String body = HttpRequest.post(url).form("token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2tlamlubGlhbm1lbmcuY29tL2FjY291bnQvZ29vZHMvZXN0YWJsaXNoIiwiaWF0IjoxNzI5NjYyOTU2LCJleHAiOjE3MzIyNTQ5NTYsIm5iZiI6MTcyOTY2Mjk1NiwianRpIjoia09hOHdUNGxRNFU4S1lYSyIsInN1YiI6MjY3LCJwcnYiOiI2N2QzMTA2MDM5N2RlYmQ0MjIzNjMxYzExNzU0Y2UxNGM2NjM0MmMxIiwidXNlciI6eyJ0eXBlIjoidXNlciIsInNhbHQiOiIyNDMyM2E4MjI2YzdlNjUzMzM0NGVjNzk5MjFjYzA5YiJ9fQ.jEu-wO4LosYt5rI7e9OmrKDINnbRi7opPqD-fVFOTQI").form("image",file).execute().body();
//        return body;
//    }
    public static File convert(byte[] byteArray, String s) throws IOException {
        File file = File.createTempFile(s.substring(0, 13), ".jpg");
//        imgUrl = file.getPath();
        Path path = Paths.get(file.getAbsolutePath());
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(byteArray);
        }catch (Exception e){

        }
        return file;
    }


}
